package net.ibizsys.psstudio.ms.springboot.api.srv.mqttapi.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;

/**
 * 实体服务API[PSDEVCENTER]控制类
 */
@RestController
@RequestMapping("/wechat")
public class WeChatRestController {

    /**
     * 凭据(需要缓存)默认7200秒有效期
     */
    public static String access_token = null;
    /**
     * 凭证是否还有效
     */
    public static Boolean isInvalidAccessToken = false;
    /**
     * 签名票据(需要缓存)默认7200秒有效期
     */
    public static String jsapi_ticket = null;
    /**
     * 凭证是否还有效
     */
    public static Boolean isInvalidJsApiTicket = false;
    /**
     * 企业微信应用ID
     */
    public String appId = "ww41b9cbca11ed5dbb";

    /**
     * 钉钉登录请求
     * 
     * @param code
     * @return
     * @throws ApiException
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login(@RequestParam final String code) throws ApiException {
        final String userId = this.getUserId(code);
        if (userId != null) {
            return userId;
        }
        return "用户Id获取失败";
    }

    /**
     * 获取配置参数
     * 
     * @param code
     * @return
     * @throws ApiException
     */
    // @RequestMapping(value = "config", method = RequestMethod.GET)
    // public String getConfig(@RequestParam final String url) throws ApiException {
    //     JSONObject obj = new JSONObject();
    //     String ticket = this.getJsApiTicket();
    //     Long timestamp = new Date().getTime();
    //     String nonceStr = this.getRandomString(10);
    //     String signature = this.getSha1(
    //             "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url);
    //     obj.put("appid", this.appId);
    //     obj.put("nonceStr", nonceStr);
    //     obj.put("timestamp", timestamp);
    //     obj.put("signature", signature);
    //     return obj.toJSONString();
    // }

    /**
     * 获取用户唯一标识
     * 
     * @param authCode
     * @return
     * @throws ApiException
     */
    protected String getUserId(final String authCode) throws ApiException {
        final String access_token = this.getAccessToken();
        String userId = null;
        if (access_token != null) {
            JSONObject json = this.get("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="
                    + this.getAccessToken() + "&code=" + authCode);
            Integer errCode = json.getInteger("errcode");
            if (errCode == 0) {
                userId = json.getString("UserId");
            } else if (errCode == 42001) {
                WeChatRestController.isInvalidAccessToken = false;
                return this.getUserId(authCode);
            }

        }
        return userId;
    }

    /**
     * 获取企业应用签名票据
     * 
     * @return
     */
    // protected String getJsApiTicket() {
    //     if (WeChatRestController.jsapi_ticket == null) {
    //         String accessToken = this.getAccessToken();
    //         JSONObject json = this
    //                 .get("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + accessToken);
    //         Integer errCode = json.getInteger("errcode");
    //         if (errCode == 0) {
    //             WeChatRestController.jsapi_ticket = json.getString("ticket");
    //         } else if (errCode == 42001) {
    //             WeChatRestController.isInvalidAccessToken = false;
    //             return this.getJsApiTicket();
    //         }
    //     }
    //     return WeChatRestController.jsapi_ticket;
    // }

    /**
     * 获取凭据
     * 
     * @return
     */
    protected String getAccessToken() {
        if (WeChatRestController.access_token == null || !WeChatRestController.isInvalidAccessToken) {
            JSONObject json = this.get(
                    "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww41b9cbca11ed5dbb&corpsecret=f9W6tP3Fk8r872xH4mlehOxpIKSFoN_cpNHVy7_QmsY");
            Integer errCode = json.getInteger("errcode");
            if (errCode == 0) {
                WeChatRestController.access_token = json.getString("access_token");
                WeChatRestController.isInvalidAccessToken = true;
            }
        }
        return WeChatRestController.access_token;
    }

    /**
     * 发送get请求
     * 
     * @param url
     * @param param
     * @return
     */
    protected JSONObject get(String url) {
        RestTemplate restTemplate = new RestTemplate();
        return JSONObject.parseObject(restTemplate.getForEntity(url, String.class).getBody());
    }

    /**
     * Sha1签名算法(临时查找，需替换)
     * 
     * @param str
     * @return
     */
    // public String getSha1(String str) {
    //     if (str == null || str.length() == 0) {
    //         return null;
    //     }
    //     char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    //     try {
    //         MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
    //         mdTemp.update(str.getBytes("UTF-8"));

    //         byte[] md = mdTemp.digest();
    //         int j = md.length;
    //         char buf[] = new char[j * 2];
    //         int k = 0;
    //         for (int i = 0; i < j; i++) {
    //             byte byte0 = md[i];
    //             buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
    //             buf[k++] = hexDigits[byte0 & 0xf];
    //         }
    //         return new String(buf);
    //     } catch (Exception e) {
    //         return null;
    //     }
    // }

    /**
     * 获取指定位数随机字符串
     * 
     * @param length
     * @return
     */
    // public String getRandomString(int length) {
    //     // 随机字符串的随机字符库
    //     String KeyString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    //     StringBuffer sb = new StringBuffer();
    //     int len = KeyString.length();
    //     for (int i = 0; i < length; i++) {
    //         sb.append(KeyString.charAt((int) Math.round(Math.random() * (len - 1))));
    //     }
    //     return sb.toString();
    // }

}